package com.tb.Service.impl;

import com.tb.DTO.ResetPasswordDTO;
import com.tb.DTO.userDTO;
import com.tb.constant.MessageConstant;
import com.tb.entity.user;
import com.tb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.tb.Service.UserService;

import javax.security.auth.login.AccountNotFoundException;
import java.util.List;

@Service
@Component
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /*
     * 用户登录
     */
    public user login(userDTO userDTO) throws AccountNotFoundException {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        user user = userMapper.userByUsername(username);
        if (user == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);// 账号不存在
        }
        if (!password.equals(user.getPassword())) {
            throw new AccountNotFoundException(MessageConstant.PASSWORD_ERROR);// 密码错误
        }
        return user;

    }

    /*
     * 用户注册
     */
    public void register(userDTO userDTO) {
        userMapper.register(userDTO);
    }

    /*
     * 修改密码
     */
    public void resetPassword(ResetPasswordDTO resetPasswordDTO) {
        // 先获取前端传过来的数据
        String oldPassword = resetPasswordDTO.getOldPassword();
        String newPassword = resetPasswordDTO.getNewPassword();
        // 创建一个新的user对象，用来查询数据库的旧密码
        user user = userMapper.userByUsername(resetPasswordDTO.getUsername());
        if (!oldPassword.equals(user.getPassword())) {
            // 如果前端传过来的旧密码和数据库中的旧密码不一致，则抛出异常
            throw new RuntimeException(MessageConstant.OLDPASSWORD_ERROR);
        }
        userMapper.resetPassword(newPassword, resetPasswordDTO.getUsername());

    }

    @Override
    public user getById(Long id) {
        return userMapper.getById(id);
    }

    @Override
    public List<user> getUserList() {
        return userMapper.getUserList();
    }
}
